package com.example.demo.commons.core.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.URLUtil;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.Map;
import java.util.Objects;


/**
 * <p> url操作 </p>
 *
 * @author tanyunpeng
 * @date 2021/11/18
 */
public class LocalURLUtils extends URLUtil {

    /**
     * 获取URL的参数
     */
    public static Map<String, String> getParams(final String url) {
        if (StringUtils.isNotBlank(url) && url.contains("?")) {
            String params = url.substring(url.indexOf("?") + 1);
            return Maps.newHashMap(Splitter.on("&").withKeyValueSeparator("=").split(params));
        }
        return Maps.newHashMap();
    }

    /**
     * 获取网关转发到微服务的请求协议
     */
    public static String getProtoByGateway(final HttpServletRequest request) {
        return StringUtils.defaultString(request.getHeader("X-Client-Proto"), request.getHeader("x-client-proto"));
    }

    /**
     * 获取网关转发到微服务的请求域名
     */
    public static String getHostByGateway(final HttpServletRequest request) {
        return StringUtils.defaultString(request.getHeader("X-Forwarded-Host"), request.getHeader("x-forwarded-host"));
    }

    /**
     * 拼接url
     *
     * @param request 请求信息
     * @param host    需要替换的域名
     * @param path    跳转的路径：非必填。默认路径为空
     * @param params  追加的参数：非必填，默认不追加
     */
    public static String joinUrl(final HttpServletRequest request, final String host,
                                 final String path, final Map<String, String> params) {
        return joinUrl(request, null, host, path, params);
    }

    /**
     * 拼接url
     *
     * @param request  请求信息
     * @param protocol 协议
     * @param host     需要替换的域名
     * @param path     跳转的路径：非必填。默认路径为空
     * @param params   追加的参数：非必填，默认不追加
     */
    public static String joinUrl(final HttpServletRequest request, final String protocol, final String host,
                                 final String path, final Map<String, String> params) {
        StringBuilder builder = new StringBuilder();
        //协议
        if (StringUtils.isNotBlank(protocol)) {
            builder.append(protocol);
        } else {
            builder.append(request.getScheme());
        }
        builder.append("://").append(host);

        //拼接路径,null：原始path，""：是不追加path，其他替换path
        if (Objects.isNull(path)) {
            builder.append(request.getServletPath());
        } else if (!"".equals(path)) {
            builder.append(path);
        }

        boolean isFirst = true;
        //组装原始参数
        String queryString = request.getQueryString();
        if (StringUtils.isNotBlank(queryString)) {
            isFirst = false;
            builder.append("?").append(queryString);
        }
        //追加参数
        if (CollectionUtil.isNotEmpty(params)) {
            for (String key : params.keySet()) {
                if (StringUtils.isNotBlank(key) && Objects.nonNull(params.get(key))) {
                    if (isFirst) {
                        isFirst = false;
                        builder.append("?");
                    } else {
                        builder.append("&");
                    }
                    builder.append(key).append("=").append(params.get(key));
                }
            }
        }
        return builder.toString();
    }

    /**
     * 拼接url
     *
     * @param sourceUrl 原始url
     * @param host      需要替换的域名：非必填，默认使用原始值
     * @param path      跳转的路径：非必填。默认路径为空
     * @param params    追加的参数：非必填，默认不追加
     */
    public static String joinUrl(final String sourceUrl, final String host, final String path,
                                 final Map<String, String> params) {
        StringBuilder builder = new StringBuilder();

        URL url = URLUtil.url(sourceUrl);
        builder.append(url.getProtocol()).append("://");
        //拼接host
        if (StringUtils.isNotBlank(host)) {
            builder.append(host);
        } else {
            builder.append(url.getHost());
        }
        //拼接路径,null：原始path，""：是不追加path，其他替换path
        if (Objects.isNull(path)) {
            builder.append(url.getPath());
        } else if (!"".equals(path)) {
            builder.append(path);
        }

        //组装原始参数
        Map<String, String> paramMap = LocalURLUtils.getParams(sourceUrl);
        //追加参数
        if (CollectionUtil.isNotEmpty(params)) {
            paramMap.putAll(params);
        }
        boolean isFirst = true;
        for (String key : paramMap.keySet()) {
            if (StringUtils.isNotBlank(key) && Objects.nonNull(paramMap.get(key))) {
                if (isFirst) {
                    isFirst = false;
                    builder.append("?");
                } else {
                    builder.append("&");
                }
                builder.append(key).append("=").append(paramMap.get(key));
            }
        }
        return builder.toString();
    }
}
